from django.shortcuts import render
from .models import *
from django.core.paginator import Paginator
from utils.wrapper import *
from .functions import *
from django.http import JsonResponse
from django.db import transaction


# 故事主页
def index(request):
    # 按更新时间倒序列获取餐厅故事
    try:
        all_stories = Story.objects.get_all_stories()
    except:
        pass
    else:
        # 创建分页器
        paginator = Paginator(all_stories,3)
        page_now = get(request,"page","1")
        stories_now = paginator.page(page_now)

    return render(request, 'stories/stories.html', locals())

# 故事具体页
def story(request):
    mess = get_messages(request)
    # 获取故事id
    story_id = get(request,"id","1")
    # 从数据库获取该故事
    try:
        story = Story.objects.get_one_story(story_id)
        story_responses = StoryResponse.objects.get_5_response(story.id, 0)
    except:
        pass
    return render(request, 'stories/story.html', locals())

# 故事评论表单提交
def response_form(request):
    # 验证用户输入数据合法性
    if check_response_input(request):
        # 创建保存点
        save_point = transaction.savepoint()
        try:
            # 存入数据库
            StoryResponse.objects.save_response(request)
            # 更新评论数
            # 更改故事评论数
            Story.objects.update_story_response_num(request)
            # 提交操作
            transaction.savepoint_commit(save_point)
            return JsonResponse({"ret": 1})
        except:
            # 如果操作出错，滚回去
            transaction.savepoint_rollback(save_point)
            pass

# 点赞功能,ajax
def dish_praise(request):
    try:
        new_praise = Story.objects.update_story_praise(request)
        return JsonResponse({"ret":new_praise})
    except:
        pass

# 查看更多评论
def show_more_response(request):
    story_id = get(request, "story_id")
    re_ok_num = get(request,"re_ok_num")
    try:
        # 从数据库再查出五条数据返回
        more_responses = StoryResponse.objects.get_5_response(story_id,re_ok_num)
    except:
        pass
    else:
        if more_responses:
            # 组装数据为json格式
            re_list = make_json(more_responses)
            return JsonResponse({"ret": re_list})
        else:
            return JsonResponse({"ret":0})